package org.lc.platform.boot.annotation.aspect;

import cn.hutool.core.util.ObjUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.lc.platform.base.constant.LcConstant;
import org.lc.platform.base.util.LoggerUtil;
import org.lc.platform.boot.annotation.SaveLog;
import org.lc.platform.base.enums.LogCategoryEnum;
import org.lc.platform.boot.util.LcAuthUtils;
import org.lc.platform.boot.util.LcWebUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 系统日志，切面处理类
 */
@Aspect
@Component
public class SaveLogAspect {

    @Pointcut("@annotation(org.lc.platform.boot.annotation.SaveLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        try {
            saveSysLog(point);
        } catch (Exception e) {
            System.out.println("EE:" + e.getMessage());
        }
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SaveLog syslog = method.getAnnotation(SaveLog.class);
        if (syslog != null) {
            var response = LcWebUtils.getResponse();
            if (response != null) {
                String id = null;
                if (ObjUtil.isNotNull(LcAuthUtils.getCurrentUser())) {
                    id = LcAuthUtils.getCurrentUser().getUserId();
                }
                String logs = LoggerUtil.createEncoderLogger(id, syslog.value().getValue(), syslog.enabledResponse());
                response.addHeader(LcConstant.X_LOG_ID, logs);
            }
        }
    }
}
